package com.sunchangpeng.server.bio.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TimeServerHandler implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(TimeServerHandler.class);

    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);

            String body = in.readLine();
            LOGGER.info("The time server receive order : {}", body);

            String currentTime = String.valueOf(System.currentTimeMillis());
            out.println(currentTime);
        } catch (IOException e) {
            LOGGER.error("", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error("", e);
                }

                in = null;
            }

            if (out != null) {
                out.close();
                out = null;
            }

            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e) {
                    LOGGER.error("", e);
                }

                this.socket = null;
            }
        }
    }
}
